package com.simons.module.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.simons.common.utils.code.JWTUtil;
import com.simons.common.utils.code.TokenInfo;
import com.simons.module.configure.GlobalConfig;


/**
 * 无状态shiro域
 */
public abstract class StatelessRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StatelessToken;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        //进行无状态用户验证
        StatelessToken statelessToken = (StatelessToken)authenticationToken;
        String token =  statelessToken.getToken();

        TokenInfo tokenInfo = JWTUtil.verifyToken(token, TokenInfo.class, GlobalConfig.TOKEN_SECRET);
        if (tokenInfo != null) {
            return new SimpleAuthenticationInfo(tokenInfo, statelessToken.getToken(),  super.getName());
        }else{
            throw new AuthenticationException("token获取失败");
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //进行当前用户授权
        TokenInfo tokenInfo = (TokenInfo)principals.getPrimaryPrincipal();
        String userId = tokenInfo.getUserId();
        List<String> permStrList = this.getPermissionList(userId);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permStrList);

        return authorizationInfo;
    }

    /**
     * 对外提供的获取权限列表的接口
     * @param userId
     * @return
     */
    protected abstract List<String> getPermissionList(String userId);

}